package com.qingke.example;

import java.io.IOException;
import java.util.HashSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qingke.dao.ChatDao;
import com.qingke.pojo.User;

/**
 * Servlet implementation class UserListServlet
 */
@WebServlet("/UserListServlet")
public class UserListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public UserListServlet() {
        super();
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		HashSet<String> usernames=(HashSet<String>)request.getServletContext().getAttribute("userList");
		if(usernames==null){
			usernames=new HashSet<String>();
		}
		String name=(String)request.getSession().getAttribute("currentUser");
		System.out.println("get username session for username");
		System.out.println(name);
		ChatDao cd =new ChatDao();
		User user=cd.login(name);
		String nickname=user==null?"":user.getName();
		String line= "me:"+nickname+",";
		
		for(String username:usernames){
			User u=cd.login(username);
			line += u.getName()+",";
		}
		line=line.equals("")?line:line.substring(0,line.length()-1);
		response.getWriter().println(line);
		cd.close();
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
